<?php
namespace app\mpbase\library;

use app\mpbase\service\Config as ConfigService;
use app\mpbase\service\Wechat as WechatService;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\WechatAutoreply;
use app\common\model\WechatConfig;
use app\common\model\WechatContext;
use app\common\model\WechatResponse;
use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\console\command\make\Model;
use think\Controller;
use think\Log;
use think\Request;

/**
 * 微信卡券 相关接口
 */
class WechatCard
{
    protected $app = null;
    protected $miniProgram = null;
    protected $appletId = null;
    protected $options = [];

    public function __construct()
    {
        //公众号初始化
        $appletId = Request::instance()->header('appletId');
        $appletId = input('appletId', $appletId);
        //如果不存在 到Session 中取appletid (后台Session)
        $appletId == null && $appletId = session('applet_info.appletid');
        $this->appletId = $appletId;

        //获取公众号配置信息
        $this->options = ConfigService::load($appletId,true);
        $this->app = new Application($this->options);
        $this->miniProgram = $this->app->mini_program;
    }

    //获取卡券列表
    public function cardList()
    {
        $offset = input('offset',0);
        $count = input('count',5);
        $card = $this->app->card;
        //CARD_STATUS_NOT_VERIFY,待审核；
        //CARD_STATUS_VERIFY_FAIL,审核失败；
        //CARD_STATUS_VERIFY_OK，通过审核；
        //CARD_STATUS_USER_DELETE，卡券被商户删除；
        //CARD_STATUS_DISPATCH，在公众平台投放过的卡券；
        $result = $card->lists($offset, $count, 'CARD_STATUS_VERIFY_OK');
        $result = json_decode($result,true);
        if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
            $cardIdList = $result['card_id_list'];
            $cardList = [];
            foreach ($cardIdList as $cardId) {
                $res = $card->getCard($cardId);
                $cardInfo = json_decode($res,true);
                array_push($cardList,$cardInfo['card']);
            }
            $result = $cardList;
        }
        return $result;
    }

    //领取卡券 签名
    public function addCardExt($cardId = '')
    {
        $cardId = input('card_id',$cardId);
        $card = $this->app->card;
        $result = $card->attachExtension($cardId);
        return $result;
    }

    /* 获取用户卡券列表 .. 无法获取用户OpenID*/
    public function userCardList($openId,$cardId = '')
    {
        $card = $this->app->card;
//        $result = $card->getUserCards($openId,$cardId);
        $result = $card->getUserCards("oWhGnjr1ep6Wd0F6SEh6jAwvLUVo",$cardId);
        return json_decode($result,true);
    }

    //创建卡券
    public function createCard($cardType,$baseInfo,$especial)
    {
        $card = $this->app->card;
        $result = $card->create($cardType, $baseInfo, $especial);
        return json_decode($result,true);
    }

    //
    public function createLandingPage($banner, $pageTitle, $canShare, $cardList)
    {
        try{
            $card = $this->app->card;
            $result = $card->createLandingPage($banner, $pageTitle, boolval($canShare), 'SCENE_H5', json_decode($cardList,true));
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "fail",
            ];
        }
    }

    //上传Logo
    public function uploadImage($path)
    {
        $material = $this->app->material;
        $result = $material->uploadImage($path);
        return json_decode($result,true);
    }

    //同步卡券数据
    public function synchData()
    {
        $wechatCard = $this->app->card;
        //CARD_STATUS_NOT_VERIFY,待审核；
        //CARD_STATUS_VERIFY_FAIL,审核失败；
        //CARD_STATUS_VERIFY_OK，通过审核；
        //CARD_STATUS_USER_DELETE，卡券被商户删除；
        //CARD_STATUS_DISPATCH，在公众平台投放过的卡券；
        $result = $wechatCard->lists(0, 100, ['CARD_STATUS_VERIFY_OK','CARD_STATUS_DISPATCH']);
        $result = json_decode($result,true);
        if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
            $cardIdList = $result['card_id_list'];
            $count = 0;
            foreach ($cardIdList as $cardId) {
                $res = $wechatCard->getCard($cardId);
                if($res['errcode'] == 0 && $result['errmsg'] == 'ok') {
                    $card = json_decode($res, true);
                    $cardModel = model('wechat_card');
                    if($card['card']['card_type'] != 'MEMBER_CARD')
                        $count += $cardModel->synchCard($card['card']);
                }
            }
            return $count;
        }else{
            return $result;
        }
    }

    //删除卡券
    public function delete($cardId)
    {
        $card = $this->app->card;;
        $result = $card->delete($cardId);
        return json_decode($result,true);
    }

    //卡券Code解码
    public function decryptCode($code)
    {
        $card = $this->app->card;
        $result = $card->decryptCode($code);
        return json_decode($result,true);
    }

    //校验卡券是否可用
    public function checkCode($code, $checkConsume=false, $cardId='')
    {
        try{
            $card = $this->app->card;
            $result = $card->getCode($code,$checkConsume,$cardId);
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                '_code' => 200,
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "ok",
                "can_consume" => false,
                "user_card_status" => "DELETE"
            ];
        }
    }

    //核销卡券
    public function consumeCode($code, $cardId = null)
    {
        try{
            $card = $this->app->card;
            $result = $card->consume($code,$cardId);
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                '_code' => 200,
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "ok",
                "can_consume" => false,
                "user_card_status" => "DELETE"
            ];
        }
    }

    //禁用卡券
    public function disabledCode($code, $cardId = '')
    {
        try{
            $card = $this->app->card;
            $result = $card->disable($code,$cardId);
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                '_code' => 200,
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "ok",
                "can_consume" => false,
                "user_card_status" => "DELETE"
            ];
        }
    }

    //用户开卡字段设置
    public function activateUserForm($cardId,$requiredForm = [], $optionalForm = [] )
    {
        try{
            if(isset($requiredForm['common_field_id_list']))
                $requiredForm['common_field_id_list'] = explode(',',$requiredForm['common_field_id_list']);
            if(isset($optionalForm['common_field_id_list']))
                $optionalForm['common_field_id_list'] = explode(',',$optionalForm['common_field_id_list']);
            $card = $this->app->card;
            $result = $card->activateUserForm($cardId,
                ['required_form'=>$requiredForm],['optional_form'=>$optionalForm]);
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                '_code' => 200,
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "ok",
                "can_consume" => false,
                "user_card_status" => "DELETE"
            ];
        }
    }

    //获取用户开卡信息
    public function getActivateTempInfo($activateTicket)
    {
        try{
            $card = $this->app->card;
            $result = $card->getActivateTempInfo($activateTicket);
            return json_decode($result,true);
        }catch(HttpException $e){
            return [
                '_code' => 200,
                'msg' => $e->getMessage(),
                "errcode" => 0,
                "errmsg" => "ok",
                "can_consume" => false,
                "user_card_status" => "DELETE"
            ];
        }
    }
}